package com.shxy.rlzy.controller;


import com.shxy.rlzy.common.lang.Result;
import com.shxy.rlzy.entity.Role;
import com.shxy.rlzy.entity.RoleMenu;
import com.shxy.rlzy.service.IRoleMenuService;
import com.shxy.rlzy.service.IRoleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author tanhao
 * @since 2021-08-16
 */
@RestController
@RequestMapping("/role-menu")
public class RoleMenuController extends BaseController {

    private IRoleService roleService;
    private IRoleMenuService roleMenuService;

    @Autowired
    public void setRoleService(IRoleService roleService) {
        this.roleService = roleService;
    }
    @Autowired
    public void setRoleMenuService(IRoleMenuService roleMenuService) {
        this.roleMenuService = roleMenuService;
    }

    /**
     * 设置角色可以访问的菜单
     * @param menuIds
     * @return
     */
    @PostMapping("/setRoleMenus/{roleId}")
    @PreAuthorize("hasAuthority('sys:role:perm')")
    public Result setRoleMenus(@PathVariable Long roleId, @RequestBody List<Long> menuIds) {
        // 1、获取用户信息
        Role role = roleService.getById(roleId);
        if(role == null) {
            return Result.fail("角色不存在!");
        }
        // 2、admin用户权限不能设置
        if(role.getCode().equals("admin")) {
            return Result.fail("禁止设置管理员权限！");
        }
        // 3、设置用户菜单
        roleMenuService.setRoleMenus(roleId, menuIds);
        // 4、返回结果
        return Result.succ("设置成功!");
    }

    @GetMapping("/init")
    @PreAuthorize("hasRole('ROLE_admin')")
    public Result initRoleMenus() {
        roleMenuService.initRoleMenus();
        return Result.succ("初始化成功!");
    }

    /**
     * 获取角色可访问菜单id
     * @param roleId
     * @return
     */
    @GetMapping("/list/{roleId}")
    @PreAuthorize("hasAuthority('sys:menu:update')")
    public Result listIds(@PathVariable Long roleId) {
        // 获取角色能访问的菜单编号列表
        List<Long> ids = roleMenuService
                .listByRoleId(roleId)
                .stream().map(RoleMenu::getMenuId)
                .collect(Collectors.toList());
        return Result.succ(ids);
    }
}
